package ft.app.gtig.gui.article;

import com.haulmont.cuba.core.app.DataService;
import com.haulmont.cuba.core.entity.FileDescriptor;
import com.haulmont.cuba.core.global.LoadContext;
import com.haulmont.cuba.core.global.Metadata;
import com.haulmont.cuba.gui.WindowManager;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.components.actions.BaseAction;
import com.haulmont.cuba.gui.components.actions.ItemTrackingAction;
import com.haulmont.cuba.gui.components.actions.RemoveAction;
import com.haulmont.cuba.gui.data.CollectionDatasource;
import com.haulmont.cuba.gui.data.DataSupplier;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.gui.upload.FileUploadingAPI;
import com.haulmont.cuba.gui.xml.layout.ComponentsFactory;

import ft.app.gtig.entity.Article;
import ft.app.gtig.service.QiNiuFileStorageService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

public class ArticleEdit extends AbstractEditor<Article> {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Inject
    private FileUploadingAPI fileUploadingAPI;

    @Inject
    private QiNiuFileStorageService qiNiuFileStorageService;

    @Inject
    private DataSupplier dataSupplier;
    @Inject
    private DataService dataService;
    @Inject
    private Metadata metadata;

    @Inject
    private Datasource<Article> dsArticle;

    @Inject
    private ComponentsFactory componentsFactory;

    @Inject
    private FileMultiUploadField multiUploadField;

    @Inject
    private FlowBoxLayout imagesFlowBox;





    @Override
    public void init(Map<String, Object> params) {



        multiUploadField.addQueueUploadCompleteListener(() -> {

            StringBuilder images = new StringBuilder(333);

            for (Map.Entry<UUID, String> entry : multiUploadField.getUploadsMap().entrySet()) {
                UUID fileId = entry.getKey();
                String fileName = entry.getValue();

                FileDescriptor srcFd = fileUploadingAPI.getFileDescriptor(fileId, fileName);

                FileDescriptor dstFd = dataSupplier.commit(srcFd);

                qiNiuFileStorageService.uploadFile(fileUploadingAPI.getFile(fileId), dstFd.getId().toString());

                images.append(dstFd.getId());
                images.append(",");
            }

            if (images.length() > 0) {
                getItem().setImages(images.toString());
                displayImages();
            }

            showNotification("Uploaded files: " + multiUploadField.getUploadsMap().values(), NotificationType.HUMANIZED);
            multiUploadField.clearUploads();
        });

        multiUploadField.addFileUploadErrorListener(event ->
                showNotification("File upload error", NotificationType.HUMANIZED));
    }

    @Override
    protected void postInit() {
        displayImages();
    }

    private void displayImages() {
        imagesFlowBox.removeAll();
        if (getItem().getImages() == null) {
            return;
        }

        String[] imagesId = StringUtils.split(getItem().getImages(), ',');
        if (imagesId.length == 0) {
            return;
        }

        for (String imgId : imagesId) {
            UUID fileId = UUID.fromString(imgId);
            FileDescriptor fd = dataService.load(LoadContext.create(FileDescriptor.class).setId(fileId));
            if (fd == null || fd.isDeleted()) {
                continue;
            }

            VBoxLayout embedded = createEmbedded(fd);
            if (embedded == null) {
                continue;
            }

            imagesFlowBox.add(embedded);
        }
    }

    private VBoxLayout createEmbedded(FileDescriptor imageFile) {

        VBoxLayout vBoxLayout = componentsFactory.createComponent(VBoxLayout.class);
        vBoxLayout.setWidth(null);

        Embedded embedded = componentsFactory.createComponent(Embedded.class);

        try {
            embedded.setType(Embedded.Type.IMAGE);
            embedded.setSource(imageFile.getName(), qiNiuFileStorageService.downloadFile(imageFile));

            vBoxLayout.add(embedded);

            Button button = componentsFactory.createComponent(Button.class);
            button.setAlignment(Alignment.TOP_CENTER);
            button.setCaption("Clear");
            button.setAction(new BaseAction("hello") {
                @Override
                public void actionPerform(Component component) {
                    imagesFlowBox.remove(vBoxLayout);
//                    vBoxLayout.setVisible(false);
                    ArticleEdit.this.clearImage(imageFile);
                }
            });
            vBoxLayout.add(button);

            return vBoxLayout;
        } catch (IOException e) {
            log.error("createEmbedded error.", e);
            return null;
        }
    }

    private void clearImage(FileDescriptor imageFile) {
        StringBuilder images = new StringBuilder(333);
        String[] srcImages = getItem().getImages().split(",");
        for (String image : srcImages) {
            if (StringUtils.equals(image, imageFile.getId().toString())) {
                continue;
            }
            images.append(image);
            images.append(",");
        }

        getItem().setImages(images.toString());
    }



}